package role

import (
	"context"
	"github.com/gogf/gf/v2/util/gconv"
	"goAdminV1/api/role/v1"
	"goAdminV1/internal/dao"
	"goAdminV1/utility"
)

func (c *ControllerV1) RoleInfo(ctx context.Context, req *v1.RoleInfoReq) (res *v1.RoleInfoRes, err error) {
	// 根据角色ID查询角色信息
	role := &v1.RoleInfoRes{}
	err = dao.CaRoles.Ctx(ctx).Where("id", req.Id).Scan(role)
	if err != nil {
		return nil, utility.Error(utility.CodeOperation, err)
	}

	var permissions []int
	rows, err := dao.CaRoleHasPermissions.Ctx(ctx).
		Where("role_id", req.Id).
		Fields("permission_id").
		All()
	if err != nil {
		return nil, utility.Error(utility.CodeOperation, err)
	}

	for _, row := range rows {
		permissionId := gconv.Int(row["permission_id"])
		permissions = append(permissions, permissionId)
	}

	// 构造返回结果
	res = &v1.RoleInfoRes{
		Id:          role.Id,
		RoleName:    role.RoleName,
		Identify:    role.Identify,
		ParentId:    role.ParentId,
		Description: role.Description,
		DataRange:   role.DataRange,
		CreatorId:   role.CreatorId,
		CreatedAt:   utility.FormatTimestamp(role.CreatedAt, ""), // 转换时间戳为日期格式字符串
		UpdatedAt:   utility.FormatTimestamp(role.UpdatedAt, ""), // 转换时间戳为日期格式字符串
		Permission:  permissions,                                 // 角色关联的权限列表
	}

	return res, nil
}
